package com.mingqijia.gassafety.job.job.equipment;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gap.cache.redis.RedisCache;
import com.mingqijia.gassafety.db.entity.Dtu;
import com.mingqijia.gassafety.db.entity.DtuAep;
import com.mingqijia.gassafety.db.entity.RecordController;
import com.mingqijia.gassafety.db.influxdb.config.InfluxDBConfiguration;
import com.mingqijia.gassafety.db.mapper.DtuAepMapper;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.db.mapper.RecordControllerMapper;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.job.service.aep.EquipmentAepService;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName EquipmentAepJob.java
 * @Description 设备数据同步
 * @createTime 2022年5月10日
 */
@Configuration
@EnableScheduling
@Slf4j
public class EquipmentAepJob {

    @Autowired
    RedisCache redisCache;
    @Autowired
    RedisCacheExt redisUtil;
    @Autowired
    DtuAepMapper dtuAepMapper;
    @Autowired
    DtuMapper dtuMapper;
    @Autowired
    EquipmentAepService equipmentAepService;
    @Value(value = "${gassafety.aep.url}")
    public String targetUrl;
    @Autowired
    InfluxDBConfiguration influxDBConnect;
    @Autowired
    RecordControllerMapper recordControllerMapper;

    public static final String format = "yyyy-MM-dd HH:mm:ss";

    /**
     * 更新设备激活状态    0 0/1 * * * ?
     */
    //@Scheduled(cron = "${gassafety.warnStrategy.job.equipmentActivateStatus}")
    public void equipmentActivateStatus() {

        log.info("equipmentActivateStatus--start--------");
        String key = Constants.UPDATE_EQUIPMENT_ACTIVATE;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
            if (acquire) {
                try {
                    List<DtuAep> dtus = dtuAepMapper.selectByStatus();
                    log.info("equipmentActivateStatus-本次要处理的数据：{}", JSONObject.toJSONString(dtus));
                    if (!CollectionUtil.isEmpty(dtus)) {
                        for (DtuAep dtuAep : dtus) {
                            Map<String, Object> res = new HashMap<>();
                                if (!StringUtils.isEmpty(dtuAep.getDeviceId())) {
                                res = equipmentAepService
                                        .get(new HashMap<>(), "/" + dtuAep.getDeviceId());
                            }
                            res.put("result", true);
                            if ((boolean) res.get("result")) {
                                log.info("equipmentActivateStatus-deviceId:{},activateTime:{}", dtuAep.getDeviceId(), dtuAep.getActivateTime());
                                if (StringUtils.isEmpty(dtuAep.getActivateTime())) {
                                    dtuAep.setActivateStatus(1);
                                    String imei = dtuAep.getIMEI();
                                    RecordController recordController = recordControllerMapper.selectByImei(imei,dtuAep.getSpId());
                                    log.info("equipmentActivateStatus-recordController:{}", JSONObject.toJSONString(recordController));
                                    if (recordController!=null) {
                                        Object o = recordController.getRecordAt();
                                        DateTime parse = DateUtil.parse(o + "");
                                        String formatDate = DateUtil.format(parse, "yyyy-MM-dd HH:mm:ss");
                                        UpdateWrapper<Dtu> wrapper = new UpdateWrapper<>();
                                        wrapper.lambda().or().eq(Dtu::getIsDeleted, 0)
                                                .eq(Dtu::getIMEI, dtuAep.getIMEI());
                                        Dtu dtu = new Dtu();
                                        //查询有效期
                                        Dtu d = dtuMapper.selectByImei(imei, "");
                                        dtu.setExpirationTime(DateUtil
                                                .offsetMonth(parse, StringUtils.isEmpty(d.getValidity())?0:d.getValidity() * 12).toString(format));
                                        dtuMapper.update(dtu, wrapper);
                                        dtuAep.setActivateTime(formatDate);
                                        dtuAepMapper.updateById(dtuAep);
                                        log.info("equipmentActivateStatus-更新：{}的激活时间:{}",
                                                imei, JSONObject.toJSONString(dtuAep));
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.info("equipmentActivateStatus-error:{}", e);
                }finally {
                    redisUtil.del(key);
                }
            }
        } catch (Exception e) {
            log.info("equipmentActivateStatus-error:{}", e);
        }

        log.info("equipmentActivateStatus--end--------");
    }

}
